<template>
    <div class="book-manage">
        <div class="toolbar">
            <el-input v-model="search" placeholder="搜索书名/作者/ISBN" style="width:240px;margin-right:12px;" clearable
                @keyup.enter="onSearch" />
            <el-button type="success" class="search-btn" @click="onSearch" style="margin-right:12px;">
                搜索
            </el-button>
            <el-button type="primary" @click="openDialog('add')">新增图书</el-button>
            <el-button color="blue" @click="onExportExcel" style="margin-left:8px;">导出Excel</el-button>
        </div>
        <el-table :data="pagedBooks" style="width:100%;margin-top:16px;" border stripe
            @selection-change="onSelectionChange" :loading="tableLoading" ref="bookTable" height="500px"
            :header-cell-style="{ textAlign: 'center', background: '#f5f7fa', fontWeight: 'bold' }"
            :cell-style="{ textAlign: 'center' }" fixed-header>
            <el-table-column type="selection" width="40" :selectable="selectableBook" />
            <el-table-column prop="title" label="书名" min-width="120" fixed="left" />
            <el-table-column prop="author" label="作者" min-width="100" />
            <el-table-column prop="isbn" label="ISBN" min-width="120" />
            <el-table-column prop="category" label="分类" min-width="80">
                <template #default="scope">
                    {{ scope.row.category?.name || '' }}
                </template>
            </el-table-column>
            <el-table-column prop="publisher" label="出版社" min-width="120">
                <template #default="scope">
                    {{ scope.row.publisher?.name || '' }}
                </template>
            </el-table-column>
            <el-table-column prop="publishYear" label="出版年" min-width="80" />
            <el-table-column prop="status" label="状态" min-width="80">
                <template #default="scope">
                    <el-tag
                        :type="scope.row.status === '在馆' ? 'success' : (scope.row.status === '借出' ? 'warning' : 'info')">
                        {{ scope.row.status }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" min-width="140" fixed="right">
                <template #default="{ row }">
                    <el-button size="small" @click="openDialog('edit', row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="onDelete(row)"
                        :disabled="row.status !== '在馆'">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div style="margin:16px 0;display:flex;align-items:center;">
            <el-button type="danger" size="small" :disabled="multipleSelection.length === 0"
                @click="onBatchDelete">批量删除</el-button>
            <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="[10, 20, 50]"
                :total="books.length" layout="total, sizes, prev, pager, next, jumper" style="margin-left:auto;"
                @current-change="onPageChange" @size-change="onPageSizeChange" background prev-text="上一页"
                next-text="下一页" />
        </div>
        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑图书' : '新增图书'" width="500px">
            <el-form :model="editForm" :rules="rules" ref="formRef" label-width="90px">
                <el-form-item label="书名" prop="title">
                    <el-input v-model="editForm.title" />
                </el-form-item>
                <el-form-item label="作者" prop="author">
                    <el-input v-model="editForm.author" />
                </el-form-item>
                <el-form-item label="ISBN" prop="isbn">
                    <el-input v-model="editForm.isbn" />
                </el-form-item>
                <el-form-item label="分类" prop="category">
                    <el-select v-model="editForm.categoryId" filterable placeholder="请选择分类">
                        <el-option v-for="c in categories" :key="c.id" :label="c.name" :value="c.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="出版社" prop="publisher">
                    <el-select v-model="editForm.publisherId" filterable placeholder="请选择出版社">
                        <el-option v-for="p in publishers" :key="p.id" :label="p.name" :value="p.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="出版年" prop="publishYear">
                    <el-input-number v-model="editForm.publishYear" :min="1900" :max="2100" />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-select v-model="editForm.status" :disabled="isEdit && editForm.status === '借出'">
                        <el-option label="在馆" value="在馆" />
                        <el-option label="借出" value="借出" />
                        <el-option label="维修中" value="维修中" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="onSave">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as XLSX from 'xlsx'

const books = ref([])
const categories = ref([])
const publishers = ref([])
const search = ref('')
const dialogVisible = ref(false)
const editForm = ref({})
const isEdit = ref(false)
const tableLoading = ref(false)
const multipleSelection = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const bookTable = ref(null)
const formRef = ref()

const rules = {
    title: [{ required: true, message: '请输入书名', trigger: 'blur' }],
    author: [{ required: true, message: '请输入作者', trigger: 'blur' }],
    isbn: [{ required: true, message: '请输入ISBN', trigger: 'blur' }],
    category: [{ required: true, message: '请选择分类', trigger: 'change' }],
    publisher: [{ required: true, message: '请选择出版社', trigger: 'change' }],
    publishYear: [{ required: true, message: '请输入出版年', trigger: 'blur' }],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const pagedBooks = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    return books.value.slice(start, start + pageSize.value)
})

const fetchBooks = async (keyword = '') => {
    tableLoading.value = true
    let url = '/books' // 修正为正确的接口路径（去掉多余的 /api）
    try {
        const res = await axios.get(url)
        if (keyword) {
            books.value = res.data.filter(b =>
                b.title.includes(keyword) ||
                b.author.includes(keyword) ||
                b.isbn.includes(keyword)
            )
        } else {
            books.value = res.data
        }
    } catch (e) {
        books.value = []
        ElMessage.error('获取图书数据失败')
    }
    tableLoading.value = false
    currentPage.value = 1
}
const fetchCategories = async () => {
    const res = await axios.get('/categories')
    categories.value = res.data
}
const fetchPublishers = async () => {
    const res = await axios.get('/publishers')
    publishers.value = res.data
}
onMounted(() => {
    fetchBooks()
    fetchCategories()
    fetchPublishers()
})
const onSearch = () => {
    fetchBooks(search.value)
}
const openDialog = (type, row) => {
    if (categories.value.length === 0 || publishers.value.length === 0) {
        ElMessage.warning('请稍候，分类和出版社数据正在加载...')
        return
    }
    if (type === 'add') {
        editForm.value = {
            title: '',
            author: '',
            isbn: '',
            categoryId: null,
            publisherId: null,
            publishYear: new Date().getFullYear(),
            status: '在馆'
        }
        isEdit.value = false
    } else if (type === 'edit' && row) {
        editForm.value = {
            ...row,
            categoryId: row.category?.id || row.category,
            publisherId: row.publisher?.id || row.publisher
        }
        isEdit.value = true
    }
    dialogVisible.value = true
}
const onEdit = (row) => {
    openDialog('edit', row)
}
const onSelectionChange = (val) => {
    multipleSelection.value = val
}
const onPageChange = (page) => {
    currentPage.value = page
}
const onPageSizeChange = (size) => {
    pageSize.value = size
    currentPage.value = 1
}
const onBatchDelete = async () => {
    if (multipleSelection.value.length === 0) return
    const notDeletable = multipleSelection.value.filter(row => row.status !== '在馆')
    if (notDeletable.length > 0) {
        ElMessage.error('只能批量删除“在馆”状态的图书')
        return
    }
    try {
        await ElMessageBox.confirm(`确定要删除选中的${multipleSelection.value.length}本图书吗？`, '批量删除', { type: 'warning' })
        for (const row of multipleSelection.value) {
            await axios.delete(`/books/${row.id}`)
        }
        ElMessage.success('批量删除成功')
        fetchBooks(search.value)
        if (bookTable.value) bookTable.value.clearSelection()
    } catch (e) {
        ElMessage.error('批量删除失败')
    }
}
const onSave = async () => {
    formRef.value.validate(async valid => {
        if (!valid) return
        const form = editForm.value
        if (!form.title || !form.author || !form.isbn || !form.categoryId || !form.publisherId) {
            ElMessage.error('请填写完整信息')
            return
        }
        if (!/^[0-9]{10,13}$/.test(form.isbn)) {
            ElMessage.error('ISBN 格式应为10~13位数字')
            return
        }
        try {
            const payload = {
                ...form,
                category: categories.value.find(c => c.id === form.categoryId),
                publisher: publishers.value.find(p => p.id === form.publisherId)
            }
            if (isEdit.value && form.id) {
                await axios.put(`/books/${form.id}`, payload)
                ElMessage.success('编辑成功')
            } else {
                await axios.post('/books', payload)
                ElMessage.success('新增成功')
            }
            dialogVisible.value = false
            fetchBooks(search.value)
        } catch (e) {
            if (e.response && e.response.data && e.response.data.message) {
                ElMessage.error(e.response.data.message)
            } else {
                ElMessage.error('保存失败')
            }
        }
    })
}
const onDelete = async (row) => {
    if (row.status === '借出') {
        ElMessage.error('该书籍正在借出，无法删除')
        return
    }
    if (row.status === '维修中') {
        ElMessage.error('该书籍维修中，无法删除')
        return
    }
    try {
        await axios.delete(`/books/${row.id}`)
        ElMessage.success('删除成功')
        fetchBooks(search.value)
    } catch (e) {
        if (e.response && e.response.status === 500) {
            ElMessage.error('该书籍有借阅记录，无法删除')
        } else {
            ElMessage.error('删除失败')
        }
    }
}
const onExportExcel = () => {
    if (!books.value || books.value.length === 0) {
        ElMessage.warning('没有可导出的图书数据')
        return
    }
    // 导出主要字段，分类和出版社导出为名称
    const data = books.value.map(b => ({
        书名: b.title,
        ISBN: b.isbn,
        作者: b.author,
        出版社: b.publisher?.name || (typeof b.publisher === 'string' ? b.publisher : ''),
        分类: b.category?.name || (typeof b.category === 'string' ? b.category : ''),
        状态: b.status
    }))
    const ws = XLSX.utils.json_to_sheet(data)
    const wb = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(wb, ws, '图书列表')
    XLSX.writeFile(wb, `图书列表_${new Date().toISOString().slice(0, 10)}.xlsx`)
}
// 多选时仅允许“在馆”状态
const selectableBook = (row) => row.status === '在馆'
</script>

<style scoped>
.book-manage {
    padding: 24px;
}

.toolbar {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
}
</style>
